package com.xiaozhengkeji.colastartboot.api;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;

import com.xiaozhengkeji.colastartboot.base.redis.VerifyBaseRedis;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 开放Api
 */
@Slf4j
@RestController
@RequestMapping("/web/open")
public class OpenApi {
    public VerifyBaseRedis verifyBaseRedis;

    @Autowired
    public OpenApi(VerifyBaseRedis verifyBaseRedis) {
        this.verifyBaseRedis = verifyBaseRedis;
    }

    /**
     * 生成验证码
     */
    @ApiOperation("生成验证码")
    @GetMapping("GenerateVerificationCode")
    public void GenerateVerificationCode(@ApiParam("当前毫秒的时间戳 例:1630231441052") @RequestParam("date") String date,
                                         HttpServletResponse response) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 50);
        /*将此验证码Tap的正确验证码写入Redis,并设置60秒缓存*/
        verifyBaseRedis.setVerificationCode(date, lineCaptcha.getCode());
        try {
            lineCaptcha.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
